<?php
/**
 * Created by PhpStorm.
 * User: 吴登科
 * Date: 2018/10/18
 * Time: 17:52
 * 用户申请发票
 */

namespace Api\Controller;

use Think\Controller;
use think\Session;

class InvoiceController extends Controller
{
    public $customer_id = '';
    public $store_id = 0;

    /*
     * 初始化
     */
    public function _initialize()
    {
        if (session('?customer_id') && session('?STORE_ID')) {
            $this->customer_id = session('customer_id');//用户id
            $this->store_id = session('STORE_ID');//店铺id
        }
    }

    /**
     * 用户开票历史列表
     */
    public function userInvoiceList()
    {
        $store_id = 1;
        $customer_id = '20181015105435446971';

        if ($customer_id) {
            //用户可开发票订单总金额
            $invoice_total_money = M('dishes_order')->where(['invoice_status' => 0, 'customer_id' => $customer_id, 'store_id' => $store_id])->sum('total_price');
            $data['invoice_total_money'] = $invoice_total_money;

            //用户已开发票和申请中发票信息列表
            $list = M('invoice')->field('invoice_id,invoice_title_type,invoice_money,status,create_time,atime')->where(['store_id' => $store_id, 'customer_id' => $customer_id])->select();
            foreach ($list as $key => $val) {
                if ($val['invoice_title_type'] == 1) {
                    $list[$key]['invoice_title_type'] = '个人';
                } else {
                    $list[$key]['invoice_title_type'] = '企业';
                }

                if ($val['status'] == 0) {
                    $list[$key]['status'] = '申请中';
                } else {
                    $list[$key]['status'] = '已开票';
                }
            }
//            print_r($list);die;

            $data['list'] = $list;

            if (!empty($list)) {
                $this->ajaxReturn(['state' => 1, 'msg' => '获取成功', 'data' => $data]);
            } else {
                $this->ajaxReturn(['state' => 0, 'msg' => '没有开票历史']);
            }
        } else {
            $this->ajaxReturn(['state' => -1, 'msg' => '对不起请登录']);
        }
    }

    /**
     * 用户发票抬头
     */
    public function userInvoiceTitle()
    {
        $store_id = 1;
        $customer_id = '20181015105435446971';

        $invoice_title_info = M('invoice_title')->field('id,invoice_title,invoice_type,taxpayer')->where(['customer_id' => $customer_id, 'store_id' => $store_id])->find();
        $arr = array(
            1 => '增值税普通发票',
            2 => '增值税电子发票',
            3 => '增值税专用发票'
        );
        $invoice_title_info['invoice_type'] = $arr[$invoice_title_info['invoice_type']];
//        print_r($invoice_title_info);
        if (!empty($invoice_title_info)) {
            $this->ajaxReturn(['state' => 1, 'msg' => '获取成功', 'data' => $invoice_title_info]);
        } else {
            $this->ajaxReturn(['state' => 0, 'msg' => '暂无抬头信息']);
        }
    }

    /**
     * 编辑发票抬头页面
     */
    public function edit()
    {
        $id = I('get.id');//发票抬头id
        if ($id) {
            $invoice_title_info = M('invoice_title')->where(['id' => $id])->find();
            if (!empty($invoice_title_info)) {
                $this->ajaxReturn(['state' => 1, 'msg' => '获取成功', 'data' => $invoice_title_info]);
            } else {
                $this->ajaxReturn(['state' => 0, 'msg' => '暂无抬头信息']);
            }
        }
    }


    /**
     * 用户添加编辑发票抬头信息
     */
    public function saveInvoiceTitle()
    {
        $store_id = 6;
        $customer_id = '20181010175617709310';

        $action = I('post.action');//add添加发票信息，默认编辑发票
        $data['store_id'] = $store_id;
        $data['customer_id'] = $customer_id;
        $data['invoice_title'] = I('post.invoice_title');//抬头
        $data['invoice_title_type'] = I('post.invoice_title_type');//抬头类型1个人2企业
        $data['invoice_type'] = I('post.invoice_type');//发票类型1增值税普通发票2增值税专用发票3组织增值税普通发票
        $data['taxpayer'] = I('post.taxpayer');//纳税人识别号
        $data['company_address'] = I('post.company_address');//企业地址
        $data['company_phone'] = I('post.company_phone');//企业电话
        $data['bank'] = I('post.bank');//企业开户银行
        $data['bank_account'] = I('post.bank_account');//企业开户银行账号
        $data['create_time'] = time();//创建时间

        if ($action) {
            if ($action == 'add') {//添加抬头
                //判断是否重复添加
                $check = M('invoice_title')->where(['customer_id' => $customer_id])->find();
                if ($check) {
                    $this->ajaxReturn(['state' => 0, 'msg' => '已存在请不要重复添加']);
                }

                $row = M('invoice_title')->add($data);
                if ($row) {
                    $this->ajaxReturn(['state' => 1, 'msg' => '添加抬头成功']);
                } else {
                    $this->ajaxReturn(['state' => 0, 'msg' => '添加失败请检查']);
                }
            }
        } else {//编辑抬头
            if ($data['invoice_title_type'] == 1) {
                $data['invoice_title'] = '个人';
            }
            $row = M('invoice_title')->where(['store_id' => $store_id, 'customer_id' => $customer_id])->save($data);
            if ($row) {
                $this->ajaxReturn(['state' => 1, 'msg' => '编辑抬头成功']);
            } else {
                $this->ajaxReturn(['state' => 0, 'msg' => '编辑失败请检查']);
            }
        }
    }


    /**
     * 我的-申请发票页面
     */
    public function applyInvoice()
    {
        $store_id = 6;
        $customer_id = '20181011094823781242';

        //取当前用户未开票订单信息
        $where['store_id'] = $store_id;
        $where['customer_id'] = $customer_id;
        $where['incoice_status'] = 0;
        $where['order_state'] = 2;
        $where['_logic'] = 'AND';
        $user_order_list = M('dishes_order')->field('id,order_no,total_price,pay_time')->where($where)->select();

        foreach ($user_order_list as $key => $value) {
            $user_order_list[$key]['store_name'] = M('store')->where(['store_id' => $store_id])->getField('store_name');
        }
//        print_r($user_order_list);die;
        if (!empty($user_order_list)) {
            $this->ajaxReturn(['state' => 1, 'msg' => '获取成功', 'data' => $user_order_list]);
        } else {
            $this->ajaxReturn(['state' => 0, 'msg' => '暂无可开票订单']);
        }
    }

    /**
     * 开票信息页面
     */
    public function invoiceInfo()
    {
        $store_id = 6;
        $customer_id = '20181015105435446971';

        $order_ids = I('get.order_ids/a', []);//用户选中要开票的订单id

        if (!empty($order_ids)) {
            $data = [];
            $data['invoice_money'] = M('dishes_order')->where(['id' => ['in', $order_ids]])->sum('total_price'); //开票总金额
            $data['order_ids'] = implode(',', $order_ids);
//            print_r($data);die;

            //取当前用户发票抬头信息
            $user_invoice_title_info = M('invoice_title')->where(['customer_id' => $customer_id, 'store_id' => $store_id])->find();
//          var_dump($user_invoice_title_info);die;

            if ($user_invoice_title_info != null) {
                switch ($user_invoice_title_info['invoice_type']) {
                    case 1:
                        $user_invoice_title_info['invoice_type'] = '企业增值税普通发票';
                        break;
                    case 2:
                        $user_invoice_title_info['invoice_type'] = '增值税专用发票';
                        break;
                    case 3:
                        $user_invoice_title_info['invoice_type'] = '组织增值税普通发票';
                        break;
                    default:
                        $user_invoice_title_info['invoice_type'] = '企业增值税普通发票';
                }
            } else {
                $this->ajaxReturn(['state' => -2, 'msg' => '参数错误请检查']);
            }

            if ($user_invoice_title_info['invoice_title_type'] == 1) {
                $user_invoice_title_info['invoice_title_type'] = '个人';
                $user_invoice_title_info['invoice_type'] = '增值税普通发票';
            } else {
                $user_invoice_title_info['invoice_title_type'] = '企业';
            }

            $data['user_invoice_title_info'] = $user_invoice_title_info;

            if (!empty($data)) {
                $this->ajaxReturn(['state' => 1, 'msg' => '获取成功', 'data' => $data]);
            } else {
                $this->ajaxReturn(['state' => 0, 'msg' => '获取失败请检查']);
            }
        } else {
            $this->ajaxReturn(['state' => -1, 'msg' => '缺少参数请检查']);
        }
    }

    /**
     * 提交申请信息
     */
    public function submitInvoice()
    {
        $store_id = 7;
        $this->customer_id = '20180817171949939503';

        $order_ids = I('post.order_ids');//开票订单id
        $invoice_money = I('post.invoice_money');//开票金额
        $is_einvoice = I('post.is_einvoice');//是否为电子发票0否1是
        $email = I('post.email');//邮箱地址
        $invoice_content = I('post.invoice_content');//发票内容

        //取当前用户发票抬头信息
        $user_invoice_title_info = M('invoice_title')->where(['customer_id' => $this->customer_id, 'store_id' => $store_id])->find();
//          print_r($user_invoice_title_info);die;

        //取用户默认邮寄地址信息的收件人，电话，地址。
        $address_info = M('address')->where(['customer_id' => $this->customer_id, 'is_default' => 1])->find();
//        print_r($address_info);die;

        if (!empty($user_invoice_title_info) && !empty($address_info)) {
            $data['store_id'] = $store_id;
            $data['customer_id'] = $this->customer_id;
            $data['order_ids'] = $order_ids;
            $data['invoice_title_type'] = $user_invoice_title_info['invoice_title_type'];
            $data['invoice_type'] = $user_invoice_title_info['invoice_type'];
            $data['invoice_title'] = $user_invoice_title_info['invoice_title'];
            $data['invoice_money'] = $invoice_money;
            $data['invoice_content'] = $invoice_content;
            $data['taxpayer'] = $user_invoice_title_info['taxpayer'];
            $data['company_address'] = $user_invoice_title_info['company_address'];
            $data['company_phone'] = $user_invoice_title_info['company_phone'];
            $data['bank'] = $user_invoice_title_info['bank'];
            $data['bank_account'] = $user_invoice_title_info['bank_account'];
            $data['email'] = $email;
            $data['address'] = $address_info['province'] . $address_info['city'] . $address_info['county'] . $address_info['address'];
            $data['phone'] = $address_info['mobile'];
            $data['consignee'] = $address_info['name'];
            $data['is_einvoice'] = $is_einvoice;
            $data['create_time'] = time();

            //保存申请发票信息
            $row = M('invoice')->add($data);
            if ($row > 0) {
                $this->ajaxReturn(['state' => 1, 'msg' => '保存成功', 'data' => $data]);
            } else {
                $this->ajaxReturn(['state' => 0, 'msg' => '保存失败请检查']);
            }
        } else {
            $this->ajaxReturn(['state' => -1, 'msg' => '缺少参数请检查']);
        }
    }

    /**
     * 用户地址列表
     */
    public function addressList()
    {
        $this->customer_id = '20180817171949939503';

        if ($this->customer_id) {
            //获取当前用户创建的收货地址列表
            $data = M('address')->where(['customer_id' => $this->customer_id])->order('is_default desc')->select();
            $count = M('address')->where(['user_id' => $this->customer_id, 'is_default' => 1])->count(); // 看看有没默认收货地址

            if ((count($data) > 0) && ($count == 0)) $data[0]['is_default'] = 1;// 如果没有设置默认收货地址, 则第一条设置为默认收货地址
        } else {
            $this->ajaxreturn(array('state' => -1, 'msg' => '你还没有登录请登录'), 'json');
        }

        if (!empty($data)) {
            $this->ajaxreturn(['state' => 1, 'msg' => '获取收货地址成功', 'data' => $data], 'json');
        } else {
            $this->ajaxreturn(['state' => 0, 'msg' => '获取收货地址失败'], 'json');
        }
    }

    /**
     * 地址 新增 和 修改
     */
    public function addressSave()
    {
        if (IS_POST) {
            $this->customer_id = '20181015105435446971';

            $type = I("post.type"); //操作类型 add:新增 edit:修改
            $map['customer_id'] = $this->customer_id;
            //分割区域字符串转为数组
            $area_arr = explode('/', trim(I('post.area')));//省市县地区名
            $map['province'] = $area_arr[0];
            $map['city'] = $area_arr[1];
            $map['county'] = $area_arr[2];
            $map['address'] = trim(I('post.address'));//详细地址
            $map['zipcode'] = trim(I('post.zipcode'));//邮编
            $map['name'] = trim(I('post.name'));//收货人姓名
            $map['mobile'] = trim(I('post.mobile'));//收货人手机号
            $map['is_default'] = I('post.is_default');//是否为默认地址

            if ($type == 'add') {//新增收货地址
                //统计收货地址是否超过10条
                $count = M('address')->where(['customer_id' => $this->customer_id])->count();
                if ($count >= 10) $this->ajaxReturn(['status' => -2, 'msg' => '你已添加10条收货地址超出限制']);

                //判断是否添加的收货地址是第一个
                $moren = M("address")->where(["customer_id" => $map['customer_id'], "is_default" => 1])->find();
                if (!$moren) $map['is_default'] = 1;

                //先设置全部不是默认
                if ($map['is_default'] == 1) M('address')->where(["customer_id" => $this->customer_id])->setField('is_default', 0);

                $row = M("address")->add($map);
                if ($row) {
                    $this->ajaxReturn(['state' => 1, 'msg' => '新增成功！']);
                } else {
                    $this->ajaxReturn(['state' => 0, 'msg' => '新增失败，请重新填写地址！']);
                }
            }

            if ($type == 'edit') {//修改收货地址
                $address_id = I("post.id");//收货地址id
                //先设置全部不是默认
                if ($map['is_default'] == 1) M('address')->where(["customer_id" => $this->customer_id])->setField('is_default', 0);
                $row = M("address")->where(["id" => $address_id])->save($map);
                if ($row) {
                    $this->ajaxReturn(['state' => 1, 'msg' => '更新成功！']);
                } else {
                    $this->ajaxReturn(['state' => 0, 'msg' => '更新失败，请重新填写地址！']);
                }
            }
        } else {
            $this->ajaxReturn(['state' => -1, 'msg' => '操作失败，请填写内容！']);
        }
    }

    /**
     * 设置默认收货地址
     */
    public function addressSetDefault()
    {
        $this->customer_id = '20181015105435446971';
        $address_id = I("get.id");
        //先设置全部不是默认
        $row = M('address')->where(["customer_id" => $this->customer_id])->setField('is_default', 0);

        if ($address_id > 0) {
            $row = M("address")->where(["id" => $address_id, 'customer_id' => $this->customer_id])->setField('is_default', 1);
        }

        if ($row) {
            $this->ajaxReturn(['status' => 1, 'msg' => '设置成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '设置失败']);
        }
    }


    /**
     * 收货地址删除
     */
    public function addressDelete()
    {
        $address_id = I("get.id");
        $row = M("address")->where(["id" => $address_id])->delete();
        if ($row) {
            $this->ajaxReturn(['status' => 1, 'msg' => '删除成功']);
        } else {
            $this->ajaxReturn(['status' => 0, 'msg' => '删除失败']);
        }
    }
}